<template>
	<!--商户列表-->
	<main-content
		:tableHeight.sync="tableHeight"
		:otherDependenComponents="otherDependenComponents"
	>
		<template slot="query">
			<el-form
				ref="form"
				:inline="true"
				:model="queryData"
				label-width="auto"
			>
				<el-form-item :label="`${$t('merchant.merchant_name')}:`">
					<merchant-select
						v-model="queryData.merchantId"
					></merchant-select>
				</el-form-item>
				<el-form-item :label="`${$t('merchant.create_time')}:`">
					<el-date-picker
						v-model="formTime.time"
						:default-time="defaultTime"
						:end-placeholder="$t('merchant.end_time')"
						:picker-options="pickerShortcut2"
						:start-placeholder="$t('merchant.start_time')"
						align="right"
						format="yyyy-MM-dd HH:mm:ss"
						range-separator="-"
						size="medium"
						style="width: 452px"
						type="datetimerange"
					></el-date-picker>
				</el-form-item>
				<el-form-item :label="`${$t('merchant.merchant_level')}:`">
					<el-select
						v-model.trim="queryData.merchantLevelId"
						:placeholder="$t('common.select_all')"
						:popper-append-to-body="false"
						clearable
						style="width: 270px"
					>
						<el-option
							v-for="item in levelList"
							:key="item.id"
							:label="item.level"
							:value="item.id"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item :label="`${$t('merchant.merchant_status')}:`">
					<el-select
						v-model.trim="queryData.status"
						:placeholder="$t('common.select_all')"
						:popper-append-to-body="false"
						clearable
						style="width: 270px"
					>
						<el-option
							v-for="item in merchantStatusType"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button
						:loading="loading"
						icon="el-icon-search"
						size="medium"
						type="primary"
						@click="search"
					>
						{{ $t('common.search') }}
					</el-button>
					<el-button
						:loading="loading"
						icon="el-icon-refresh-left"
						size="medium"
						@click="reset"
					>
						{{ $t('common.reset') }}
					</el-button>
					<el-button
						v-if="hasPermission('801011')"
						icon="el-icon-download"
						size="medium"
						type="warning"
						@click="exportExcel"
					>
						{{ $t('common.export') }}
					</el-button>
				</el-form-item>
			</el-form>
		</template>
		<template slot="content">
			<el-table
				v-loading="loading"
				:data="dataList"
				:header-cell-style="getRowClass"
				border
				element-loading-spinner="el-icon-loading"
				:max-height="tableHeight"
			>
				<el-table-column
					:label="$t('merchant.merchant_name')"
					align="center"
					min-width="220px"
					prop="loginIp"
					show-overflow-tooltip
				>
					<template slot="header">
						{{ $t('merchant.merchant_name') }}
						<br />
						{{ $t('merchant.merchant_level') }}
					</template>
					<template slot-scope="scope">
						{{ scope.row.merchantName || '-' }}
						<br />
						<span>
							{{ scope.row.merchantLevel || '-' }}
						</span>
					</template>
				</el-table-column>
				<el-table-column
					:label="$t('merchant.merchant_code')"
					:show-overflow-tooltip="true"
					align="center"
					min-width="120px"
					prop="merchantCode"
				>
					<template slot-scope="scope">
						{{ scope.row.merchantCode || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					:label="$t('merchant.merchant_lang')"
					:show-overflow-tooltip="true"
					align="center"
					min-width="180px"
					prop="languages"
				>
					<template slot-scope="scope">
						{{
							(scope.row.languages || '-')
								.split(',')
								.map((item) =>
									typeFilter(item, 'language').replace(
										'-',
										''
									)
								)
								.join('')
						}}
					</template>
				</el-table-column>
				<el-table-column
					:label="$t('merchant.merchant_wallet')"
					:show-overflow-tooltip="true"
					align="center"
					prop="currency"
					min-width="120px"
				>
					<template slot-scope="scope">
						{{ scope.row.currency || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					label="主钱包"
					:show-overflow-tooltip="true"
					align="center"
					prop="currency"
					min-width="120px"
				>
					USDT
				</el-table-column>
				<el-table-column
					:label="$t('merchant.merchant_status')"
					align="center"
					:min-width="getWidth('80px')"
					prop="loginStatus"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<el-tag
							:type="
								scope.row.status === '1' ? 'success' : 'danger'
							"
						>
							{{ typeFilter(scope.row.status, 'merchantStatus') }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column
					:label="$t('merchant.login_ip')"
					align="center"
					min-width="130px"
					prop="loginIp"
					show-overflow-tooltip
				>
					<template slot="header">
						{{ $t('merchant.member_number') }}
						<br />
						{{ $t('merchant.agent_number') }}
					</template>
					<template slot-scope="scope">
						{{ scope.row.memberNum || '-' }}
						<br />
						{{ scope.row.proxyNum || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					prop="centerWalletBalance"
					align="center"
					label="会员现金钱包余额"
					:show-overflow-tooltip="true"
					min-width="180px"
				>
					<template slot-scope="scope">
						{{ handleCurrency(scope.row.currency.split(' ')[1]) }}
						{{
							handleNumber(
								scope.row.currency.split(' ')[1],
								scope.row.centerWalletBalance || 0
							)
						}}
					</template>
				</el-table-column>
				<el-table-column
					prop="createdBy"
					align="center"
					:label="$t('merchant.creator')"
					:show-overflow-tooltip="true"
					min-width="120px"
				>
					<template slot-scope="scope">
						{{ scope.row.createdBy || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					prop="createdAt"
					align="center"
					:label="$t('merchant.create_time')"
					:show-overflow-tooltip="true"
					min-width="180px"
				>
					<template slot-scope="scope">
						{{ scope.row.createdAt || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					prop="loginError"
					align="center"
					min-width="200px"
					:label="$t('merchant.remark')"
					:show-overflow-tooltip="true"
				>
					<template slot-scope="scope">
						{{ scope.row.remark || '-' }}
					</template>
				</el-table-column>
			</el-table>
			<!-- 分页 -->
			<el-pagination
				:current-page.sync="pageNum"
				class="pageValue"
				background
				layout="total, sizes,prev, pager, next, jumper"
				:page-size="pageSize"
				:page-sizes="pageSizes"
				:pager-count="9"
				:total="total"
				@current-change="handleCurrentChange"
				@size-change="handleSizeChange"
			></el-pagination>
		</template>
	</main-content>
</template>

<script>
import { routerNames } from '@/utils/consts'
import list from '@/mixins/list'
import dayjs from 'dayjs'
import {
	queryMerchantPageListApi,
	updateMerchantInfoApi
} from '@/api/merchant/merchant-manage/merchant-list'
import { queryMerchantLevelListApi } from '@/api/merchant/merchant-config/level-config'
import MainContent from '@/components/MainContent/index.vue'
// import BaseColumn from '@/components/TableColumns/BaseColumn'

const setSearchTime = () => [
	dayjs()
		.subtract(0, 'day')
		.startOf('day'),
	dayjs()
		.subtract(0, 'day')
		.endOf('day')
]

export default {
	name: routerNames.merchantList,
	components: {
		MainContent
		// BaseColumn
	},
	mixins: [list],
	data() {
		this.search = this.throttle(this.search, 1000)
		this.reset = this.throttle(this.reset, 1000)
		return {
			tableHeight: 480,
			otherDependenComponents: [],
			queryData: {
				merchantId: undefined,
				merchantLevelId: undefined,
				status: undefined
			},
			formTime: {
				time: setSearchTime()
			},
			levelList: [],
			dataList: []
		}
	},
	computed: {
		merchantStatusType() {
			return this.globalDics?.merchantStatus || []
		}
	},
	methods: {
		async loadData() {
			this.loading = true
			try {
				const res = await queryMerchantLevelListApi({ pageSize: 999 })
				const { code, data } = res || {}
				if (code === 200) {
					this.levelList = data?.record || []
				}
			} catch (err) {
				console.log(err)
			}

			const [startTime, endTime] = this.formTime.time || []
			let params = {
				...this.queryData,
				createdAtStart: startTime
					? dayjs(startTime).format('YYYY-MM-DD HH:mm:ss')
					: undefined,
				createdAtEnd: endTime
					? dayjs(endTime).format('YYYY-MM-DD HH:mm:ss')
					: undefined
			}
			params = {
				...this.getParams(params)
			}
			queryMerchantPageListApi(params)
				.then((res) => {
					this.loading = false
					const { code, msg } = res
					if (res && code === 200) {
						const data = res.data
						this.dataList =
							(data &&
								data.record &&
								data.record.length &&
								Object.freeze(data.record)) ||
							[]
						this.total = (data && data.totalRecord) || 0
						this.summary = data
							? data.summary
							: { count: 0, failCount: 0, successCount: 0 }
					} else {
						this.loading = false
						this.$message({
							message: res && msg,
							type: 'error'
						})
					}
				})
				.catch(() => {
					this.loading = false
				})
		},
		exportExcel() {
			const [startTime, endTime] = this.formTime.time || []
			let params = {
				...this.queryData,
				createdAtStart: startTime
					? dayjs(startTime).format('YYYY-MM-DD HH:mm:ss')
					: undefined,
				createdAtEnd: endTime
					? dayjs(endTime).format('YYYY-MM-DD HH:mm:ss')
					: undefined
			}
			params = {
				...this.getParams(params)
			}
			this.$confirm(
				`<strong>${this.$t(
					'common.is_export'
				)}</strong></br><span style='font-size:12px;color:#c1c1c1'>${this.$t(
					'common.excess_data'
				)}</span>`,
				`${this.$t('common.success_tip')}`,
				{
					dangerouslyUseHTMLString: true,
					confirmButtonText: `${this.$t('common.sure')}`,
					cancelButtonText: `${this.$t('common.cancel')}`,
					type: 'warning'
				}
			)
				.then(() => {
					updateMerchantInfoApi(params)
						.then((res) => {
							this.loading = false
							const { data, status } = res
							if (res && status === 200) {
								const { type } = data
								if (type.includes('application/json')) {
									const reader = new FileReader()
									reader.onload = (evt) => {
										if (evt.target.readyState === 2) {
											const {
												target: { result }
											} = evt
											const ret = JSON.parse(result)
											if (ret.code !== 200) {
												this.$message({
													type: 'error',
													message: ret.msg,
													duration: 1500
												})
											}
										}
									}
									reader.readAsText(data)
								} else {
									const result = res.data
									const disposition =
										res.headers['content-disposition']
									const fileNames =
										disposition && disposition.split("''")
									let fileName = fileNames[1]
									fileName = decodeURIComponent(fileName)
									const blob = new Blob([result], {
										type: 'application/octet-stream'
									})
									if (
										'download' in
										document.createElement('a')
									) {
										const downloadLink = document.createElement(
											'a'
										)
										downloadLink.download = fileName || ''
										downloadLink.style.display = 'none'
										downloadLink.href = URL.createObjectURL(
											blob
										)
										document.body.appendChild(downloadLink)
										downloadLink.click()
										URL.revokeObjectURL(downloadLink.href)
										document.body.removeChild(downloadLink)
									} else {
										window.navigator.msSaveBlob(
											blob,
											fileName
										)
									}
									this.$message({
										type: 'success',
										message: this.$t(
											'common.export_success'
										),
										duration: 1500
									})
								}
							}
						})
						.catch(() => {
							this.loading = false
						})
				})
				.catch(() => {
					this.loading = false
				})
		},
		reset() {
			this.queryData = {
				merchantId: undefined,
				merchantLevelId: undefined,
				status: undefined
			}
			this.pageNum = 1
			this.formTime.time = setSearchTime()
			this.loadData()
		}
	}
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
	text-align: center;
	color: #909399;
	font-weight: 700;
}

.login1 {
	margin-top: 0;

	span {
		margin-left: 50px;
	}
}

.login2 {
	padding-bottom: 15px;

	.fail {
		margin-left: 50px;
	}
}
</style>
